package com.ks.core.util;

/**
 * @author kingdee
 * @date 2020/2/24 19:39
 */

import java.util.*;

/**
 * 微信请求参数处理类
 * @author kingdee
 *
 */
public class RequestHandler {

    public RequestHandler() {
        parameters = new HashMap<String, String>();
    }

    protected Map<String, String> parameters;//通过该参数设置微信接口需要的参数

    public void setParameter(String parameter, String parameterValue) {
        if (parameter != null && parameter != "") {
            if (parameters.containsKey(parameter)) {
                parameters.remove(parameter);
            }
            parameters.put(parameter, parameterValue);
        }
    }

    /// <summary>
    /// 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名
    /// </summary>
    /// <param name="key">参数名</param>
    /// <param name="value">参数值</param>
    /// key和value通常用于填充最后一组参数
    /// <returns></returns>
    public String createMd5Sign(String key, String value) {
        StringBuilder sb = new StringBuilder();
        List<String> akeys = new ArrayList<String>(parameters.keySet());
        Collections.sort(akeys);
        for (String k : akeys) {
            String v = parameters.get(k);
            if (null != v && "".compareTo(v) != 0
                    && "sign".compareTo(k) != 0 && "key".compareTo(k) != 0) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append(key + "=" + value);//最后拼接秘钥
        System.out.println("签名拼接的字符串" + sb.toString());
        return MD5Util.getMD5(sb.toString()).toUpperCase();
    }

    /// <summary>
    /// 输出XML
    /// </summary>
    /// <returns></returns>
    public String parseXML() {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (String k : parameters.keySet()) {
            String v = parameters.get(k);
            sb.append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
        }
        sb.append("</xml>");
        System.out.println(sb);
        return sb.toString();
    }

    public Map<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }
}
